package com.btl.sqlite;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class DbOpService {
	private SqlHelper dbhelper;

	public DbOpService(Context ctx) {
		this.dbhelper = new SqlHelper(ctx);
	}

	// 插入操作
	public void Insert(History history) {
		SQLiteDatabase db = dbhelper.getWritableDatabase();
		db.execSQL(
				"insert into history_table(username,vid,v_time,v_title,v_intro) values(?,?,?,?,?)",
				new Object[] { history.getUsername(), history.getVid(),history.getVtime(),history.getTitle(),history.getIntro()});
	}
	// 删除操作
	public void Delete(String name) {
		SQLiteDatabase db = dbhelper.getWritableDatabase();
		db.execSQL("delete from history_table where username=?", new Object[] { name });
	}



	// 查询操作
	public List<History> Query(String name) {
		//如果模糊查询，可能会返回多行，请返回集合
		List<History> list = new ArrayList<>();
		SQLiteDatabase db = dbhelper.getReadableDatabase();
		
		//db.rawQuery()返回 一个Cursor对象，这个对象类似于JavaSE中的ResultSet结果集
		Cursor cursor=db.rawQuery("select * from history_table where username= ? order by hid desc ", new String[] {name});
		while(cursor.moveToNext()){
			History history=new History();
			String username=cursor.getString(cursor.getColumnIndex("username"));
			String vid=cursor.getString(cursor.getColumnIndex("vid"));
			String vtime=cursor.getString(cursor.getColumnIndex("v_time"));
			String vtitle=cursor.getString(cursor.getColumnIndex("v_title"));
			String vintro=cursor.getString(cursor.getColumnIndex("v_intro"));
			history.setUsername(username);
			history.setVid(vid);
			history.setVtime(vtime);
			history.setTitle(vtitle);
			history.setIntro(vintro);
			list.add(history);
		}
		cursor.close();
		return list;
	}
	// 获取总记录数
	public long GetCount() {
		SQLiteDatabase db = dbhelper.getReadableDatabase();
		Cursor cursor=db.rawQuery("select count(hid) from history_table", null);
		cursor.moveToFirst();
		long count=cursor.getInt(0);
		return count;
	}
}
